<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model='falg'/> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          商品名称:<input type="text" v-model="$store.state.name" /><br />
          商品数量:<input type="text" v-model="$store.state.num" /><br />
          商品价格:<input type="text" v-model="$store.state.price" />
            <th>
              <button @click="btn4">添加</button>
            </th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <th><input type="checkbox" v-model='item.checked'/></th>
          <th>{{ item.name }}</th>
          <th>{{ item.price }}</th>
          <th>
            <button :disabled="item.num === 1" @click="btn1(index)">-</button>
            {{ item.num }}
            <button @click="btn2(index)">+</button>
          </th>
          <th>{{ item.num * item.price }}</th>
          <th>
            <button @click="btn3(index)">删除</button>
          </th>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">{{getSum}}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
       checked:false,
    };
  },
  computed: {
    arr() {
      return this.$store.state.goodList;
    },
    getSum() {
      return this.$store.state.goodList.reduce((sum, item) => {
        if (item.checked) {
             sum += item.num * item.price
        }
        return sum
         }, 0)
    },
    falg:{
      set(checked) {
         this.$store.commit('addFn5',checked)
      },
      get() {
         // 单选控制全选
         return this.$store.state.goodList.every(item =>item.checked === true)
      }
    }
  },
  methods: {
    // 减少数量
    btn1(index) {
      this.$store.commit("addFn1", index);
    },
    // 增加数量
    btn2(index) {
      this.$store.commit("addFn2", index);
    },
    // 删除
    btn3(index) {
      this.$store.commit("addFn3", index);
    },
    // 添加
    btn4() {
      this.$store.commit("addFn4");
    },
  },
};
</script>

<style></style>
